#include "Net/Socket.h"
#include "Base/Log/LogDefine.h"

CSocket::CSocket(void)
{
	mSocketFD = -1;
}

CSocket::~CSocket(void)
{
	if (mSocketFD > -1)
	{
#ifdef __WIN_PLATFORM__
		closesocket(mSocketFD);
#elif __LINUX_PLATFORM__
		::close(mSocketFD);
#endif
	}
}

int CSocket::open()
{
	mSocketFD = socket(AF_INET, SOCK_STREAM, 0);
	return mSocketFD;
}

void CSocket::setTcpNoDelay(bool is)
{
	int ret = 0;
	int opt = is ? 1 : 0;
#ifdef __WIN_PLATFORM__
	ret = setsockopt(mSocketFD, IPPROTO_TCP, TCP_NODELAY, (char*)&opt, sizeof(opt));
#elif __LINUX_PLATFORM__
	ret = setsockopt(mSocketFD, IPPROTO_TCP, TCP_NODELAY, &opt, sizeof(opt));
#endif

	if (ret < 0)
	{
		LOGE("socket:%d set tcp no delay failure error:%d", mSocketFD, ret);
	}
}

void CSocket::setReuseAddress(bool is)
{
	int ret = 0;
	int opt = is ? 1 : 0;
#ifdef __WIN_PLATFORM__
	ret = setsockopt(mSocketFD, SOL_SOCKET, SO_REUSEADDR, (char*)&opt, sizeof(opt));
#elif __LINUX_PLATFORM__
	ret = setsockopt(mSocketFD, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
#endif

	if (ret < 0)
	{
		LOGE("socket:%d set tcp reuse address failure error:%d", mSocketFD, ret);
	}
}

void CSocket::setNonBlock()
{
	int ret = 0;
#ifdef __WIN_PLATFORM__
	unsigned long ul=1;  
	int r=ioctlsocket(mSocketFD,FIONBIO,&ul);  
#elif __LINUX_PLATFORM__
	int flag = fcntl(mSocketFD, F_GETFL, 0);
	flag |= O_NONBLOCK;
	ret = fcntl(mSocketFD, F_SETFL, flag);
#endif

	if (ret < 0)
	{
		LOGE("socket:%d set nonblock failure error:%d", mSocketFD, ret);
	}

}

void CSocket::setCloseOnExec()
{
	int flag;
#ifdef __WIN_PLATFORM__

#elif __LINUX_PLATFORM__
	flag = fcntl(mSocketFD, F_GETFD, 0);
	flag |= FD_CLOEXEC;
	fcntl(mSocketFD, F_SETFD, flag);
#endif
}

void CSocket::setLinger()
{
	int ret = 0;
	struct linger ling = {0, 0};
#ifdef __WIN_PLATFORM__
	ret = setsockopt(mSocketFD, SOL_SOCKET, SO_LINGER, (char*)&ling, sizeof(ling));
#elif __LINUX_PLATFORM__
	ret = setsockopt(mSocketFD, SOL_SOCKET, SO_LINGER, &ling, sizeof(ling));
#endif

	if (ret < 0)
	{
		LOGE("socket:%d set socket linger failure error:%d", mSocketFD, ret);
	}
}

void CSocket::setIPAddress(char *pIp)
{
	if (pIp == NULL)
	{
		LOGW("in setIPAddress ip is null");
		return;
	}

	strncpy(mIPAddress, pIp, IP_LENGTH);
}
